<?php

namespace addons\csmitsm\library\xcore\xcflow\utils;

use addons\csmitsm\library\xcore\xcore\utils\XcDaoUtils;
use think\Db;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;

class XcflowallformUtils
{
    public static function queryTableinfoList($wheres = [])
    {
        $sql = Db::table(XcDatabaseUtils::appendTablePrefix("csmitsm_xcflowallform"))->where('status', '=', 'normal');
        foreach ($wheres as $where) {
            $sql->where($where[0], $where[1], $where[2]);
        }
        return $sql->select();
    }

    public static function getTableinfoByTablename($tablename)
    {
        $factTablename = XcDatabaseUtils::getFactTablename($tablename);
        $abstractTablename = XcDatabaseUtils::getAbstraceTablename($tablename);

        $list = XcDatabaseUtils::getRowBySql(XcDatabaseUtils::appendTablePrefix("csmitsm_xcflowallform"), [
            ['tablename', 'in', [$factTablename, $abstractTablename]]
        ], null, true, true, 'xid desc');
        return $list;
    }

    public static function getXcformByTablename($tablename)
    {
        $tableinfo = static::getTableinfoByTablename($tablename);
        $dao = null;
        switch ($tableinfo['xcformtype']) {
            case "flow":
            case "flowsub":
                $dao = new \app\admin\model\csmitsm\Xcflow();
                break;
            case "mdm":
                $dao = new \app\admin\model\csmitsm\Xcflowmdm();
                break;
            default:
                return null;
        }
        $xcform = XcDaoUtils::getRowById($dao, $tableinfo["xid"]);
        return $xcform;
    }

    public static function getXcformtypeFromXcform($xcform)
    {
        $xcformtype = null;

        $tablename = $xcform->getTable();
        switch ($tablename) {
            case XcDatabaseUtils::appendTablePrefix("csmitsm_xcflow"):
                $xcformtype = "flow";
                break;
            case XcDatabaseUtils::appendTablePrefix("csmitsm_xcflowmdm"):
                $xcformtype = "mdm";
                break;
        }

        return $xcformtype;
    }

    public static function getXcformByRow($row)
    {
        $dao = null;
        switch ($row["xcformtype"]) {
            case "mdm":
                $dao = new \app\admin\model\csmitsm\Xcflowmdm();
                break;
            case "flow":
            case "flowsub":
                $dao = new \app\admin\model\csmitsm\Xcflow();
                break;
        }
        if ($dao == null) {
            return null;
        }

        $xcform = XcDaoUtils::getRowById($dao, $row['xid']);
        return $xcform;
    }
}
